import React, { Component } from 'react'
import { Link } from 'react-router-dom'
import {
  Card,
  Breadcrumb,
  Form,
  Button,
  Radio,
  DatePicker,
  Table,
  Tag,
  Space,
  Modal,
  message,
} from 'antd'
import {
  EditOutlined,
  DeleteOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons'
import { articleStatus } from 'utils/constant'

import { delArticle, getArticles } from 'api/article'
import DefaultImg from 'assets/error.png'
import Channel from 'components/Channel'
const { RangePicker } = DatePicker
const { confirm } = Modal
export default class ArticleList extends Component {
  state = {
    articles: {},
  }
  reqParams = {
    page: 1,
    per_page: 10,
  }
  columns = [
    {
      title: '封面',
      dataIndex: 'cover',
      render(item) {
        const { type, images } = item
        return type === 0 ? (
          <img
            src={DefaultImg}
            alt=""
            style={{ width: 200, height: 120, objectFit: 'contain' }}
          />
        ) : (
          <img
            src={images[0]}
            alt=""
            style={{ width: 200, height: 120, objectFit: 'contain' }}
          />
        )
      },
    },
    {
      title: '标题',
      dataIndex: 'title',
    },
    {
      title: '状态',
      dataIndex: 'status',
      render(val) {
        const obj = articleStatus.find((item) => item.id === val)
        return <Tag color={obj.color}>{obj.name}</Tag>
      },
    },
    {
      title: '发布时间',
      dataIndex: 'pubdate',
    },
    {
      title: '阅读数',
      dataIndex: 'read_count',
    },
    {
      title: '评论数',
      dataIndex: 'comment_count',
    },
    {
      title: '点赞数',
      dataIndex: 'like_count',
    },
    {
      title: '操作',
      render: (data) => {
        // console.log(data)
        return (
          <Space>
            <Button
              type="primary"
              shape="circle"
              icon={<EditOutlined />}
              onClick={() =>
                this.props.history.push(`/home/publish/${data.id}`)
              }
            ></Button>
            <Button
              type="primary"
              danger
              shape="circle"
              icon={<DeleteOutlined />}
              onClick={() => this.delArt(data)}
            ></Button>
          </Space>
        )
      },
    },
  ]
  delArt = ({ id }) => {
    confirm({
      title: '温馨提示',
      icon: <ExclamationCircleOutlined />,
      content: '确认永久删除该篇文章吗？',
      onOk: async () => {
        await delArticle(id)
        this.loadArticles()
        message.success('删除文章成功')
      },
    })
  }
  onFinish = ({ status, channel_id, date }) => {
    const { reqParams } = this
    if (status !== -1) {
      Object.assign(reqParams, { status })
    } else {
      delete reqParams.status
    }
    if (channel_id !== undefined) {
      Object.assign(reqParams, { channel_id })
    } else {
      delete reqParams.channel_id
    }
    if (date) {
      Object.assign(reqParams, {
        begin_pubdate: date[0].startOf('day').format('YYYY-MM-DD HH:mm:ss'),
      })
      Object.assign(reqParams, {
        end_pubdate: date[1].endOf('day').format('YYYY-MM-DD HH:mm:ss'),
      })
    } else {
      delete reqParams.begin_pubdate
      delete reqParams.end_pubdate
    }
    reqParams.page = 1

    this.loadArticles()
  }
  componentDidMount() {
    this.loadArticles()
  }

  async loadArticles() {
    const { data: articles } = await getArticles(this.reqParams)
    this.setState({ articles })
  }
  // 分页改变
  onChange = (page, pageSize) => {
    // console.log(page, pageSize)
    this.reqParams.page = page
    this.reqParams.per_page = pageSize
    this.loadArticles()
  }
  render() {
    const {
      articles: { total_count, results, per_page, page },
    } = this.state
    return (
      <div className="atricleList">
        <Card
          title={
            <Breadcrumb separator=">">
              <Breadcrumb.Item>
                <Link to="/home">首页</Link>
              </Breadcrumb.Item>
              <Breadcrumb.Item>文章列表</Breadcrumb.Item>
            </Breadcrumb>
          }
        >
          <Form
            onFinish={this.onFinish}
            initialValues={{
              status: articleStatus[0].id,
            }}
          >
            <Form.Item label="状态" name="status">
              <Radio.Group>
                {articleStatus.map((item) => (
                  <Radio key={item.id} value={item.id}>
                    {item.name}
                  </Radio>
                ))}
              </Radio.Group>
            </Form.Item>
            {/* 频道 */}
            <Form.Item label="频道" name="channel_id">
              <Channel></Channel>
            </Form.Item>
            {/* 时间 */}
            <Form.Item label="时间" name="date">
              <RangePicker />
            </Form.Item>
            <Form.Item>
              <Button type="primary" htmlType="submit">
                筛选
              </Button>
            </Form.Item>
          </Form>
        </Card>
        <Card title={`根据筛选条件共查询到 ${total_count || 0} 条数据`}>
          <Table
            dataSource={results}
            columns={this.columns}
            rowKey={(record) => record.id}
            pagination={{
              position: ['bottomCenter'],
              total: total_count,
              current: page,
              pageSize: per_page,
              onChange: this.onChange,
            }}
          />
        </Card>
      </div>
    )
  }
}
